#include "StdAfx.h"
#include "WorldClient.h"
#include "WorldSession.h"
#include "World.h"
#include "DBSocket.h"

WorldClient::WorldClient(void)
{
	m_pListRecvMsg = new CListMsg;
	m_pListSendMsg = new CListMsg;
	m_pSession = NULL;
}

WorldClient::~WorldClient(void)
{
	Destroy();
}

void WorldClient::Destroy()
{
	m_pSession->Stop();
	closesocket(m_Socket);
	delete m_pListRecvMsg; m_pListRecvMsg = NULL;
	delete m_pListSendMsg; m_pListSendMsg = NULL;

}
void WorldClient::AuthSession(tagMessage* pMsg, DWORD dwSize)
{
 	if (m_pSession)
 	{
 		sLog.Write("Player send NC_AUTH_SESSION again\n");
 	}
 	
 	tagNC_PlayerAuthSession* p = (tagNC_PlayerAuthSession*) pMsg;	
 	m_pSession = new WorldSession(p->szName, this);
 	sWorld.AddCheckingSession(m_pSession);
 
 	tagDC_PlayerAuthSession msg;
 	strncpy(msg.szName, p->szName, 32);
 	strncpy(msg.szPassword, p->szPassword, 32);
 	sDBSocket.SendMSG2DB(&msg, msg.dwSize);
}

DWORD WorldClient::AddRecvMsg(tagMessage* pMsg, DWORD dwSize)
{
	switch(pMsg->dwHDCode)
	{
	case NC_PlayerAuthSession:
		AuthSession(pMsg, dwSize);
		break;
	default:
		m_pListRecvMsg->AddMsg(pMsg, dwSize);
	}
	return 0;
}

tagMessage* WorldClient::GetRecvMsg()
{
	return m_pListRecvMsg->GetMsg();
}

int	WorldClient::GetRecvNums()
{
	return m_pListRecvMsg->GetNums();
}
void WorldClient::ClearRecvMsg()
{
	return m_pListRecvMsg->ClearMsg();
}

void WorldClient::AddSendMsg(tagMessage* pMsg, DWORD dwSize)
{
	return m_pListSendMsg->AddMsg(pMsg, dwSize);
}

tagMessage* WorldClient::GetSendMsg()
{
	return m_pListSendMsg->GetMsg();
}

int	WorldClient::GetSendNums()
{
	return m_pListSendMsg->GetNums();
}
void WorldClient::ClearSendMsg()
{
	return m_pListSendMsg->ClearMsg();
}


DWORD WorldClient::HandleMessage()
{
	tagMessage* pMsg = GetRecvMsg();
	while(pMsg)
	{
		m_pSession->ExecuteOpcode(pMsg);
		DEL_MSG(pMsg, pMsg->dwSize);
		pMsg = (tagMessage*)GetRecvMsg();
	}
	return 0;
}